<template>
	<div>
		<game-box :gameHeight="394">
			<template #config>
				<div class="h-full w-full bg-[#2a364f] px-[12px] py-[16px]">
					<BetAmount
						v-if="!isDesktop"
						:type="type"
						:isRuning="isRuning"
						:isDisabled="isDisabled"
						:showMax="maxbet"
						:amount="amount"
						@changeMoneyDisabled="changeMoneyDisabled"
						@changeAmount="changeAmount" />
					<StartBtn
						v-if="!isDesktop"
						@handleClick="handleStart"
						stopIcon="diamonds"
						:type="type"
						:isRuning="isRuning"
						:stoping="stoping"
						:isDisabled="disabledBtn" />
					<SwitchTab
						v-if="isDesktop"
						:class="!isDesktop ? 'mt-4' : ''"
						:type="type"
						:isRuning="isRuning"
						:mute="mute"
						:rocket="rocket"
						:showMax="maxbet"
						:isDisabled="isDisabled"
						@changeMode="changeMode" />
					<div class="h-group-t"></div>
					<BetAmount
						v-if="isDesktop"
						:type="type"
						:isRuning="isRuning"
						:showMax="maxbet"
						:isDisabled="isDisabled"
						:amount="amount"
						@changeMoneyDisabled="changeMoneyDisabled"
						@changeAmount="changeAmount" />
					<div class="h-group-t" v-if="isDesktop"></div>
					<template v-if="type === 'auto'">
						<div class="h-group-t"></div>
						<LoopCount
							@changeLoop="changeLoop"
							:type="type"
							:loopNum="loopNum"
							:isRuning="isRuning"
							:isDisabled="isDisabled" />
						<div class="h-group-t"></div>
						<profit-percentage
							:isRuning="isRuning"
							:title="$t('miniGames.onwin')"
							type="profitPer"
							:isDisabled="isDisabled"
							@change="changeProfitPercentage" />
						<div class="h-group-t"></div>
						<profit-percentage
							:isRuning="isRuning"
							:isDisabled="isDisabled"
							:title="$t('miniGames.onloss')"
							type="lossPer"
							@change="changeLossPercentage" />
						<div class="h-group-t"></div>
						<stop-profitable
							@changeProfitable="changeProfitable"
							:isRuning="isRuning"
							:isDisabled="isDisabled" />
						<div class="h-group-t"></div>
						<loss-suspension
							@changeLoss="changeLoss"
							:isRuning="isRuning"
							:isDisabled="isDisabled" />
					</template>

					<div v-if="isDesktop">
						<StartBtn
							:type="type"
							:isRuning="isRuning"
							stopIcon="diamonds"
							:isDisabled="disabledBtn"
							:stoping="stoping"
							@handleClick="handleStart" />
						<div class="h-group-t"></div>
					</div>
					<SwitchTab
						v-if="!isDesktop"
						:class="!isDesktop ? 'mt-4' : ''"
						:type="type"
						:isRuning="isRuning"
						:mute="mute"
						:rocket="rocket"
						:showMax="maxbet"
						:isDisabled="isDisabled"
						@changeMode="changeMode" />
				</div>
			</template>
			<template #content>
				<div ref="gameContent" class="h-full w-full bg-[#1B2538]"></div>
			</template>
		</game-box>
		<result-dialog
			:showDialog="showResult"
			:betId="resultBetId"
			gameType="diamonds"
			:gameObj="mGame"
			@close="closeResultDialog" />
	</div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch, computed } from 'vue'
import GameBox from '../components/game-box/index.vue'
import StartBtn from '../components/common/start-button.vue'
import BetAmount from '../components/common/bet-amount.vue'
import SwitchTab from '../components/common/switch-tab.vue'
import LoopCount from '../components/common/loop-count.vue'
import stopProfitable from '../components/common/stop-profitable.vue'
import lossSuspension from '../components/common/loss-suspension.vue'
import profitPercentage from '../components/common/profit-percentage.vue'
import ResultDialog from '../components/dialog/result.vue'
import { loadJs } from '@/utils'
import { isDesktop } from '@/hooks'
import { playDiamonds, gameEndSettled } from '@/api/third/mini-games'
import { useWalletStore, useAccountStore, useAppStore } from '@/store'
// import { THIRD_GAME } from '@/constants/global-key'
import { AccountShowType } from '@/types'
import { eventBus } from '@/views/games/eventBus'
import { qlaunchUrl } from '../getUrlT'
import { showError, message, getCurrencyIcon } from '@/utils'
import { transformationAmount, calculateProfitLoss } from '../util'
import { delayGameTime, accelerateTimeInter } from '@/views/games/config'

// const currency = computed(() => walletStore.balanceCur?.currency)
const accountStore = useAccountStore()
const walletStore = useWalletStore()
const appStore = useAppStore()
const type = ref('manual')
const isRuning = ref(false)
const isDisabled = ref(true)
const isMoneyDisabled = ref(false)
const stoping = ref(false)
const loopNum = ref(0)
const profit = ref<string | number>(0)
const loss = ref<string | number>(0)
const amount = ref<string | number>(0)
const autoOneAmount = ref<string | number>(0)
const profitPer = ref<any>({ value: 0, active: 'rest' })
const lossPer = ref<any>({ value: 0, active: 'rest' })
const maxbet = ref(false)
const mute = ref(false)
const rocket = ref(false)
const timeInter = ref(delayGameTime)
const showResult = ref(false)
const resultBetId = ref('')
let mGame: any = null
const gameContent = ref(null)
let errorState = false
let interval: any = null
let languageMap: any = null
// 累计盈利亏损
const profitLossTotal = ref(0)
// 游戏返回数据
let gameBackData: any = {}

const disabledBtn = computed(() => isMoneyDisabled.value || isDisabled.value)
watch(
	() => accountStore.token,
	() => qlaunchUrl()
)
watch(
	() => appStore.lang,
	(val: string) => {
		mGame?.setLanguage(languageMap?.[val])
	}
)
const currencyIcon = computed(() => {
	const { selectedFiatCurrency, displayCryptoInFiat, selectedCryptoCurrency } =
		walletStore.walletConfig
	return displayCryptoInFiat ? selectedFiatCurrency : selectedCryptoCurrency
})
watch(currencyIcon, (val) => {
	mGame?.changeCurrencyIcon(getCurrencyIcon(val))
})
onMounted(() => {
	qlaunchUrl()
	initGame()
	eventBus.on('changeRocket', (val: any) => {
		console.log(val)
		rocket.value = val
		mGame?.setSpeedUpMode(val)
		timeInter.value = val ? accelerateTimeInter : delayGameTime
	})
	eventBus.on('changeMaxBet', (val: any) => {
		console.log(val)
		maxbet.value = val
	})
	eventBus.on('changeMute', (val: boolean) => {
		console.log(val)
		mute.value = val
		mGame?.setSoundEffect(!val)
	})
})
onUnmounted(() => {
	restTimeAuto()
	// 在组件卸载时移除监听器
	eventBus.off('changeRocket', () => {
		// 空的回调函数
	})
	eventBus.off('changeMaxBet', () => {
		// 空的回调函数
	})
	eventBus.off('changeMute', () => {
		// 空的回调函数
	})
})
const changeMoneyDisabled = (status: boolean) => {
	isMoneyDisabled.value = status
}
const restTimeAuto = (auto = false) => {
	isRuning.value = false
	isDisabled.value = false
	interval && clearTimeout(interval)
	if (auto) {
		setTimeout(() => {
			message.success('自动投注完成', { duration: 5000 })
		})
	}
}
const gameEnd = async () => {
	if (!gameBackData?.id) return
	await gameEndSettled({
		round: gameBackData?.id
	})
}
const initGame = () => {
	loadJs('/gameLib.js').then((originalGameLib: any) => {
		let Language = originalGameLib.Language
		languageMap = {
			zh: Language.ZH,
			zhTW: Language.zhTW,
			en: Language.EN
		}
		mGame = new originalGameLib.DiamondsGame({
			parentElement: gameContent.value,
			backgroundColor: '#1B2538',
			language: languageMap[appStore.lang],
			currencyIcon: getCurrencyIcon(),
			backgroundAlpha: 1,
			gamePadding: 20,
			soundEffect: true,
			speedMode: false,
			onGameEnd: () => {
				//游戏状态
				console.log('游戏结束')
				gameEnd()
			},
			//Payout方块选中的监听函数
			onPayoutSelect: () => {
				//返回投注额输入框输入的值
				return amount.value
			},
			onGameLoadEnd: () => {
				//游戏加载完成
				isDisabled.value = false
			}
		})
	})
}
const closeResultDialog = () => {
	showResult.value = false
}
const handleStart = async () => {
	profitLossTotal.value = 0
	if (errorState) {
		return
	}
	if (type.value === 'auto') {
		console.log('auto')
		if (isRuning.value) {
			stoping.value = true
			setTimeout(() => {
				stoping.value = false
				restTimeAuto(true)
			}, delayGameTime)
		} else {
			message.success('自动投注开始', { duration: 5000 })
			isRuning.value = true //控制自动按钮操作切换， true是停止按钮显示
			autoOneAmount.value = amount.value

			if (loopNum.value === 0) {
				playGame('all')
			}
			if (loopNum.value > 0) {
				playGame()
				loopNum.value--
				if (loopNum.value === 0) {
					restTimeAuto(true)
				}
			}
		}
	} else {
		console.log('开始')
		await playGame('bet')
	}
}
const playGame = async (loop: string = '') => {
	if (!accountStore.token) {
		accountStore.showAccount(AccountShowType.login)
		return
	}
	try {
		if (stoping.value) return
		isRuning.value = true
		mGame.startGame(() => {})
		const { data } = await playDiamonds({
			amount: transformationAmount(amount.value),
			currency: walletStore.balanceCur?.currency,
			identifier: 'diamonds'
		})
		gameBackData = data
		mGame.addGameNumberResult(data.id, data.state.result, data.amount)
		setTimeout(() => {
			if (loop === 'bet') {
				isRuning.value = false
			}
			// 计算是否达到盈亏阈值
			if (
				calculateProfitLoss(data, {
					type,
					amount,
					profitPer,
					lossPer,
					profit,
					loss,
					profitLossTotal,
					autoOneAmount
				})
			) {
				restTimeAuto()
				return
			}
			// 自动投注状态
			if (loop === 'all' && isRuning.value) {
				interval = setTimeout(() => {
					playGame(loop)
				}, timeInter.value)
			}
			if (loopNum.value > 0 && isRuning.value) {
				interval = setTimeout(() => {
					let lastPlay = ''
					loopNum.value--
					if (loopNum.value === 0) {
						restTimeAuto(true)
						lastPlay = 'bet'
					}
					playGame(lastPlay)
				}, timeInter.value)
			}
		}, delayGameTime)
	} catch (error: any) {
		showError(error)
		interval && clearTimeout(interval)
		isDisabled.value = false
		isRuning.value = false
	}
}
const changeLoop = (val: string) => {
	console.log(val)
	loopNum.value = parseInt(val)
}
const changeProfitable = (val: string) => {
	console.log(val, 'profit')
	profit.value = val
}
const changeProfitPercentage = (data: any) => {
	profitPer.value = data
}
const changeLossPercentage = (data: any) => {
	lossPer.value = data
}
const changeLoss = (val: string) => {
	console.log(val, 'loss')
	loss.value = val
}
const changeAmount = (val: string) => {
	console.log(val, 'amount')
	amount.value = val
}
const changeMode = (val: string) => {
	type.value = val
}
</script>
<style lang="scss" scoped>
.h-group-t {
	height: 12px;
}
.b-shadow {
	box-shadow:
		0 1px 3px 0 rgba(0, 0, 0, 0.2),
		0 1px 2px 0 rgba(0, 0, 0, 0.12);
}
.bth-style {
	color: white !important;
	&:hover {
		color: white;
		background-color: #557086;
	}
	&.n-button.n-button--disabled,
	&:active,
	&:focus {
		background-color: #3e4c68;
	}
}
</style>
